package com.qys.livesMall.security.interceptor.core;

import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.app.user.constants.RedisConstant;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.security.constants.SecConstants;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.qys.livesMall.common.constants.SysConstants.AUTHORIZATION;

@Order(3)
public class LoginInterceptor implements HandlerInterceptor {
    private static Log logger = LogFactory.getLog(LoginInterceptor.class);

    @Resource
    private RedisCache redisCache;

    //handle 前

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("***********************执行了登录拦截器*************************");
        //如果是登录请求，跳过验证
        String url = request.getRequestURI();
        logger.info("request url:" + url);
        System.err.print(url);

        String token = request.getHeader(AUTHORIZATION);

        if (token == null) {
            //未登陆向前端返回数据
            setUserErrorResponse(response, "Token cannot be empty");
            return false;
        }

        String tokenKey = CacheUtil.getKey(SecConstants.RedisKeyPrefix.TOKEN, token);
        LoginUser userInfo = redisCache.getCacheObject(tokenKey);

        //查询是否app用户
        if (userInfo == null) {
            tokenKey = CacheUtil.getKey(RedisConstant.USER_TOKEN, token);
            userInfo = redisCache.getCacheObject(tokenKey);
        }

        //缓存未获取到用户数据
        if (userInfo == null) {
            //未登陆向前端返回数据
            setUserErrorResponse(response, "The user does not exist");
            return false;
        }

        //刷新有效期
        redisCache.expire(tokenKey, 30, TimeUnit.DAYS);

        //app用户
        if (userInfo.getUserSource() == 1) {
            tokenKey = CacheUtil.getKey(RedisConstant.USER_ID_TOKEN, String.valueOf(userInfo.getUserId()));
            String cacheToken = redisCache.getCacheObject(tokenKey);
            if (!Objects.equals(cacheToken, token)) {
                //该账号已在另一地方登录
                setErrorResponse(response, "The account is already logged in in another location");
                return false;
            }
        }

        //用户加入线程
        //ThreadContext.addCurrentUser(userInfo);
        return true;
    }

    /**
     * 账号被顶
     * @param response
     * @param message
     */
    private static void setErrorResponse(HttpServletResponse response, String message) {
        message = message == null ? "Please login" : message;

        R<String> jsonResult = R.fail(ExceptionEnum.REMOTE_LOGIN.getCode(), message);

        String jsonString = JSONObject.toJSONString(jsonResult);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);

        } catch (IOException e) {
            logger.info(message, e);
        }
    }

    /**
     * 凭证过期
     * @param response
     * @param message
     */
    private static void setUserErrorResponse(HttpServletResponse response, String message) {
        message = message == null ? "Please login" : message;

        R<String> jsonResult = R.fail(ExceptionEnum.UNAUTHORIZED.getCode(), message);

        String jsonString = JSONObject.toJSONString(jsonResult);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);

        } catch (IOException e) {
            logger.info(message, e);
        }
    }
}

